'use strict'

const router = require('koa-router')();
const fs = require('fs');

function GetRouter() {
    let File = fs.readdirSync(__dirname);
    let FileRouter = File.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    });
    return FileRouter;
}

function RegisterRouter(router, FileRouter) {
    FileRouter.forEach(item => {
        let tmpFilePath = __dirname + '/' + item;
        let tmp = require(tmpFilePath);
        for (var key in tmp) {
            let tmpArr = key.split(' ');
            let tmpUrl = tmpArr[1];
            let tmpMethod = tmpArr[0];
            let tmpFunction = tmp[key];
            if (tmpMethod === 'get') {
                router.get(tmpUrl, tmpFunction);
            }
            else if (tmpMethod === 'post') {
                router.post(tmpUrl, tmpFunction);
            }
            else if (tmpMethod === 'put') {
                router.put(tmpUrl, tmpFunction);
            }
            else if (tmpMethod === 'delete') {
                router.delete(tmpUrl, tmpFunction);
            } else {

            }
        }
    });
    return router.routes();
}

module.exports=function () {
    let fn1 = GetRouter();
    let fn2 = RegisterRouter(router, fn1)
    return fn2;
}